<template>

    <d2-container type="card">





        <template slot="header">老师提成统计</template>
        

        <div class="d2-mb" style="display: block;width: 100%;position: relative;" >
           
            <el-button type="primary" @click="setYesterday">
                <d2-icon name="download"/>
                昨天
            </el-button>
            <el-button type="primary" @click="setLastMonth">
                <d2-icon name="download"/>
                上个月
            </el-button>
             <el-button type="primary" @click="exportDetail">
                <d2-icon name="download"/>
                导出明细
            </el-button>
            <el-button type="primary" @click="exportExcel">
                <d2-icon name="download"/>
                导出 Excel
            </el-button>

        <!-- <el-col :span="6" style="float: right"> -->
          <el-select 
            style="position: absolute;right:3vw;top:0vw;z-index: 100"
            v-model="school"
            filterable
            placeholder="所属校区"
            @change="schoolSelected"
            v-if="headquarter"
          >
            <el-option
              v-for="item in schoolList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>

           <el-button type="primary" @click="changeDisplayType" style="position:absolute;right:3vw;top:3vw;z-index: 100">
            {{(display == 1) ? '图表' : '表格' }}
            </el-button>
        <!-- </el-col> -->

        </div>

        <el-form :inline="true" :model="queryOption" ref="dataSearch">

            <el-form-item >
                <el-date-picker
                        v-model="queryOption.start_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width: 150px'
                        >
                </el-date-picker>
            </el-form-item>

            <el-form-item >
                <el-date-picker
                        v-model="queryOption.end_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width:150px'
                        >
                </el-date-picker>
            </el-form-item>
            <el-form-item style='width: 150px'>

            <el-select
                            v-model="queryOption.period"
                            >
                        <el-option
                                v-for="item in filterType"
                                :label="item.name"
                                :value="item.value"
                        ></el-option>
                    </el-select>
                    </el-form-item>
                     <el-form-item style='width: 150px'>

            <el-select v-if='!teacher'
                            v-model="queryOption.teacher"
                            >
                        <el-option
                                v-for="item in staffList"
                                :label="item.name"
                                :value="item._id"
                                filterable
                        ></el-option>
                    </el-select>
                    </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="formSubmit">
                    <d2-icon name="search"/>
                    查询
                </el-button>
            </el-form-item>
        </el-form>

<div style="margin-bottom: 20px" v-show="display == 0">
      <div id="course_income_2" :style="{width: '1200px', height: '400px',color:'#ccc'}">
      </div>
    </div>

        <el-table v-bind="table" style="width: 100%" v-if="display==1" :height='600'>
            <el-table-column
                    v-for="(item, index) in table.columns"
                    :key="index"
                    :prop="item.prop"
                    :label="item.label">
            </el-table-column>
        </el-table>


    </d2-container>
</template>

<script>
    import request from "@/plugin/axios";
        import { mapState } from "vuex";
                                                  import excel from "@/libs/util.excel"


    function getTodayDate() {
        let day1 = new Date();
        let s1 = day1.getFullYear()+"-" + addZero(day1.getMonth()+1) + "-" + addZero(day1.getDate()) + ' ' + addZero(day1.getHours()) + ':' + addZero(day1.getMinutes()) + ':00';
        // s1 = '2019-09-21 17:00'
        return s1
    }

    function getYesterdayDate() {
        let day1 = new Date();
        day1.setDate(day1.getDate() - 1);
        let s1 = day1.getFullYear()+"-" + addZero(day1.getMonth()+1) + "-" + addZero(day1.getDate());
        return s1
    }


    function getLastMonthDate() {
        let day1 = new Date();
        day1.setMonth(day1.getMonth() - 1);
        let s1 = day1.getFullYear()+"-" + addZero(day1.getMonth()+1) + "-" + addZero(day1.getDate());
        return s1
    }

    function getLastYearDate() {
        let day1 = new Date();
        day1.setFullYear(day1.getFullYear() - 1);
        let s1 = day1.getFullYear()+"-" + addZero(day1.getMonth()+1) + "-" + addZero(day1.getDate());
        return s1
    }

    function addZero(a){
        return a < 10 ? '0' + a : a
    }

    export default {
        data() {
            return {
                teacher:false,
                filename: __filename,
                headquarter : 0,
                schoolList : [],
                display : 1,
                table: {
                    columns: undefined,
                    data: undefined,
                    size: 'mini',
                    stripe: true,
                    border: true
                },
                filterType : [{name:'时长：日',value:'day'},{name:'时长：周',value:'week'},{name:'时长：月',value:'month'},{name:'时长：年','value':'year'}],
                payType : [{name:'支付：不限',value:-1},{name:'支付：现金',value:0},{name:'支付：银行卡',value:1},{name:'支付：微信',value:2},{name:'支付：支付宝','value':3}],
                staffList : [{name:'老师：不限',_id:-1}],
                exportData:{
columns: undefined,
                    data: undefined,
                    size: 'mini',
                    stripe: true,
                    border: true
                },
                plot : {},
                queryOption:{
                    start_time:undefined,
                    end_time:undefined,
                    period : 'day',
                    teacher : -1,
                    school : undefined
                },
            }
        },

                  computed:{
    ...mapState('d2admin/user',['info'])
  },


        methods: {
            drawLine() {
      // 基于准备好的dom，初始化echarts实例
      let myChart6 = this.$echarts.init(document.getElementById('course_income_2'))

      // 绘制图表
      myChart6.setOption({
        title: {
          text: '老师提成表'
        },
        tooltip : {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data:this.plot.name
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis : [
          {
            type : 'category',
            boundaryGap : false,
            data : this.plot.date,

          }
        ],
        yAxis : [
          {
            type : 'value',
            axisLabel:{
              formatter:`{value}元`
            }
          }
        ],
        series :this.plot.data
      })

     

    },
            formSubmit(){

                this.getInitData(this.queryOption.school)
            },

            setYesterday(){

                this.queryOption.start_time = getYesterdayDate()

                this.queryOption.end_time = getTodayDate()

                this.getInitData(this.queryOption.school)
            },

            setLastMonth(){

                this.queryOption.start_time = getLastMonthDate()

                this.queryOption.end_time = getTodayDate()

                this.getInitData(this.queryOption.school)

            },
            setLastYear(){


                this.queryOption.start_time = getLastYearDate()

                this.queryOption.end_time = getTodayDate()

                this.getInitData(this.queryOption.school)
            },


            getInitData(school) {
                var data = {start_time: this.queryOption.start_time,end_time: this.queryOption.end_time,period:this.queryOption.period}
                if ((school != undefined) && (school != 'all')){
                    data.school = school
                }

                if (this.teacher){
                    this.queryOption.teacher = this.staff
                    delete data.school
                }

                if (this.queryOption.teacher != -1){
                    data.staff = this.queryOption.teacher
                    // delete data.school
                }
                
                // if (this.teacher == true){
                //     delete data.school
                // }

                request({
                    url: "/data/getSchoolTeacherIncome",
                    method: "post",
                    data:data

                }).then(res => {
                    if(res.code==200){
                        

                        this.table.data = [{date:'区间总计',discount:res.data.data.map(function(e){return e.discount}).reduce(function(a,b){
                            return a + b}
                        ),
                        
                         commission0:res.data.data.map(function(e){return e.commission0}).reduce(function(a,b){
                            return a + b}
                        ),
                        commission1:res.data.data.map(function(e){return e.commission1}).reduce(function(a,b){
                            return a + b}
                        ),
                        commission2:res.data.data.map(function(e){return e.commission2}).reduce(function(a,b){
                            return a + b}
                        ),commission3:res.data.data.map(function(e){return e.commission3}).reduce(function(a,b){
                            return a + b}
                        )
                        ,commission4:res.data.data.map(function(e){return -e.commission4}).reduce(function(a,b){
                            return a + b}
                        ),commission5:res.data.data.map(function(e){return e.commission5}).reduce(function(a,b){
                            return a + b}
                        ),
                        price:res.data.data.map(function(e){return e.price}).reduce(function(a,b){
                            return a + b}
                        )
                         }]
                         for (var i = 0 ; i < res.data.data.length ; i++){
                            let keys = Object.keys(res.data.data[i])
                            for (var j = 0 ;j < keys.length ;j++){
                                if (keys[j] != 'date'){
                                res.data.data[i][keys[j]] = parseFloat((parseFloat( res.data.data[i][keys[j]] * 100) / 100).toFixed(1))
                                    this.table.data[0][keys[j]] = parseFloat((parseFloat( this.table.data[0][keys[j]] * 100) / 100).toFixed(1))
                                }
                            }
                        }

                        this.table.data = this.table.data.concat(res.data.data)
                        this.table.columns = res.data.columns
                        this.plot.name = []
                        for (var j = 1 ; j < res.data.columns.length ; j++){
                            this.plot.name.push(res.data.columns[j].label)
                        }
                        var bububu = []
                        for (var i = 0 ; i < res.data.data.length ; i++){
                            bububu.push(res.data.data[i])
                        }
                        bububu.sort(function(a,b){return new Date(a.date) - new Date(b.date) })
                        this.plot.date = bububu.map(function(e){return e.date})
                        this.plot.data = []
                        for (var i =0 ; i < this.plot.name.length ; i++){
                            this.plot.data.push({
                                name :res.data.columns[i + 1].label,
                                type : 'bar',
                                // stack : '总量',
                                areaStyle : {},
                                data :bububu.map(function(e){return e[res.data.columns[i + 1].prop]})
                            })
                        }
                        this.drawLine()

                    }})




            },
           


            exportDetail(params = {}) {
                var data = {start_time: this.queryOption.start_time,end_time: this.queryOption.end_time}
                if ((this.school != undefined) && (this.school != 'all')){
                    data.school = this.school
                }
                if (this.queryOption.teacher != -1){
                    data.staff = this.queryOption.teacher
                }

                request({
                    url: "/data/getSchoolCommissionDetail",
                    method: "post",
                    data:data

                }).then(res => {
                    excel.export(res.data.columns,res.data.data,'提成明细表')
                })
               
            },

            exportExcel() {
                excel.export(this.table.columns,this.table.data,'提成收入表')
                
                // this.$export.excel({
                //     columns: this.table.columns,
                //     data: this.table.data,
                //     title : '提成收入表'
                // })
                //     .then(() => {
                //         this.$message('导出表格成功')
                //     })
            },
            schoolSelected() {
      // this.getDepartmentList(1, 99999);
            var ob = this.schoolList.map(function(e){return e._id}).indexOf(this.school)
            this.queryOption.school = this.schoolList[ob]._id
            if (this.schoolList[ob]._id == 'all'){
                this.getInitData('all')
            }
            else{
                this.getInitData(this.schoolList[ob]._id)
                this.searchStaff()
            }
            
    },

  searchStaff() {   

                request({
                    url: "/staff/getStaffList",
                    method: "post",
                    data: {
                        page: 1,
                        pageSize: 1000,
                        // name: this.search.staffName,
                        school: this.queryOption.school
                    }
                }).then(res => {
                    this.staffList = [{name:'老师：不限',_id:-1}]
                    this.staffList = this.staffList.concat(res.data.staff);
                    // this.searchStaffCount = res.data.count;
                });
            },

    changeDisplayType() {
      // this.getDepartmentList(1, 99999);
      this.display = this.display == 0 ? 1 : 0
      this.drawLine()
    },
            getSchoolList(page, pageSize) {



      let data = {};
      (data.page = page), (data.pageSize = pageSize);
      request({
        url: "/school/getSchoolList",
        method: "post",
        data
      }).then(res => {
        // this.school = this.info.school[0]._id
        this.schoolList = [{name:'全部',_id:'all'}]
        this.schoolList = this.schoolList.concat(res.data.school)
        // 返回数据
      });


    },
        },


        created() {

            this.queryOption.start_time = getLastMonthDate()
            this.rights = this.info.rights.map(function(e){return e.name})
            this.queryOption.end_time = getTodayDate()
            this.staff = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
            this.school = this.info.school[0]._id
            this.queryOption.school = this.school

            let index1 = this.rights.indexOf('root') != -1
            let index5 = this.rights.indexOf('校长') != -1
            let index6 = this.rights.indexOf('报表中心') != -1
            let index2 = this.rights.indexOf('授课老师') != -1
            let index4 = this.rights.indexOf('教务老师') != -1
            let index0 = this.rights.indexOf('root') != -1
            index2 = (index2 || index4)
            index1 = index1 || index5

            index1 = index1 || index6
            
            let index3 = this.rights.indexOf('财务中心') == -1
            
            if (index0 || (this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)){
                this.headquarter = true
                this.queryOption.school = this.school
                this.getSchoolList(1,99999)
            }
            if ((!index1) && (index2)){
                this.teacher = true
                this.headquarter = false
            }

            if (!this.teacher){
                this.searchStaff()
            }
            
            if (this.staff != null){
                this.getInitData(this.info.school[0]._id)
            }
            else{
                this.$alert('','请先绑定员工')
            }

            

           




  }


        
}
</script>
<style lang="scss" scoped>
.page {
  .logo {
    width: 120px;
  }
  .btn-group {
    color: $color-text-placehoder;
    font-size: 12px;
    margin-top: 0px;
    margin-bottom: 20px;
    .btn-group__btn {
      color: $color-text-sub;
      &:hover {
        color: $color-text-main;
      }
      &.btn-group__btn--link {
        color: $color-primary;
      }
    }
  }
}
</style>